﻿using Dapper_Core.Model;
using StackExchange.Redis;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace Dapper_Core.Common
{
    public class RedisConnectionUtility
    {
        //系统自定义Key前缀
        public static readonly string SysCustomKey = Appsettings.RedisServer.CustomKey ?? "";

        //"127.0.0.1:6379,allowadmin=true
        private static readonly string RedisConnectionString = Appsettings.RedisServer.Host;

        private static readonly object Locker = new object();
        private static ConnectionMultiplexer _instance;
        private static readonly ConcurrentDictionary<string, ConnectionMultiplexer> ConnectionCache = new ConcurrentDictionary<string, ConnectionMultiplexer>();

        /// <summary>
        /// 单例获取
        /// </summary>
        public static ConnectionMultiplexer Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (Locker)
                    {
                        if (_instance == null || !_instance.IsConnected)
                        {
                            _instance = GetManager();
                        }
                    }
                }
                return _instance;
            }
        }

        /// <summary>
        /// 缓存获取
        /// </summary>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        public static ConnectionMultiplexer GetConnectionMultiplexer(string connectionString)
        {
            if (!ConnectionCache.ContainsKey(connectionString))
            {
                ConnectionCache[connectionString] = GetManager(connectionString);
            }
            return ConnectionCache[connectionString];
        }

        private static ConnectionMultiplexer GetManager(string connectionString = null)
        {
            ConnectionMultiplexer connect = null;

            if (string.Equals(Appsettings.RedisServer.Type, "Instance"))
            {
                connectionString = connectionString ?? RedisConnectionString;
                connect = ConnectionMultiplexer.Connect(connectionString);
            }
            else if (string.Equals(Appsettings.RedisServer.Type, "Cluster"))
            {
                ConfigurationOptions option = new ConfigurationOptions();
                option.Password = Appsettings.RedisServer.Password;
                foreach (string item in Appsettings.RedisServer.ClusterNodes)
                {
                    string[] array = item.Split(':', StringSplitOptions.RemoveEmptyEntries);
                    if (array.Length == 2 && Regex.IsMatch(array[1], @"\d+"))
                    {
                        option.EndPoints.Add(array[0], Convert.ToInt32(array[1]));
                    }
                }
                connect = ConnectionMultiplexer.Connect(option);
            }

            //注册如下事件
            connect.ConnectionFailed += MuxerConnectionFailed;
            connect.ConnectionRestored += MuxerConnectionRestored;
            connect.ErrorMessage += MuxerErrorMessage;
            connect.ConfigurationChanged += MuxerConfigurationChanged;
            connect.HashSlotMoved += MuxerHashSlotMoved;
            connect.InternalError += MuxerInternalError;

            return connect;
        }

        #region 事件

        /// <summary>
        /// 配置更改时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void MuxerConfigurationChanged(object sender, EndPointEventArgs e)
        {
            NlogUtility.WriteInfo(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "Redis ConfigurationChanged", "e.EndPoint=" + e.EndPoint, "DapperCore");
            //Console.WriteLine("Redis ConfigurationChanged: " + e.EndPoint);
        }

        /// <summary>
        /// 发生错误时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void MuxerErrorMessage(object sender, RedisErrorEventArgs e)
        {
            NlogUtility.WriteInfo(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "Redis ErrorMessage", "e.Message=" + e.Message, "DapperCore");
            //Console.WriteLine("Redis ErrorMessage: " + e.Message);
        }

        /// <summary>
        /// 重新建立连接之前的错误
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void MuxerConnectionRestored(object sender, ConnectionFailedEventArgs e)
        {
            NlogUtility.WriteInfo(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "Redis ConnectionRestored", "e.EndPoint=" + e.EndPoint, "DapperCore");
            //Console.WriteLine("Redis ConnectionRestored: " + e.EndPoint);
        }

        /// <summary>
        /// 连接失败 ， 如果重新连接成功你将不会收到这个通知
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e)
        {
            NlogUtility.WriteInfo(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "Redis ConnectionFailed", e.EndPoint + ", " + e.FailureType + (e.Exception == null ? "" : (", " + e.Exception.Message)), "DapperCore");
            //Console.WriteLine("Redis ConnectionFailed: " + e.EndPoint + ", " + e.FailureType + (e.Exception == null ? "" : (", " + e.Exception.Message)));
        }

        /// <summary>
        /// 更改集群
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void MuxerHashSlotMoved(object sender, HashSlotMovedEventArgs e)
        {
            NlogUtility.WriteInfo(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "Redis HashSlotMoved", "NewEndPoint=" + e.NewEndPoint + ", OldEndPoint=" + e.OldEndPoint, "DapperCore");
            //Console.WriteLine("Redis HashSlotMoved: NewEndPoint" + e.NewEndPoint + ", OldEndPoint" + e.OldEndPoint);
        }

        /// <summary>
        /// redis类库错误
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void MuxerInternalError(object sender, InternalErrorEventArgs e)
        {
            NlogUtility.WriteInfo(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "Redis InternalError", "e.Exception.Message=" + e.Exception.Message, "DapperCore");
            //Console.WriteLine("Redis InternalError: Message" + e.Exception.Message);
        }

        #endregion 事件
    }
}
